/*-------------------------------------------------
 * Companion include for silkajax.js to provide 
 * utility functions for text/ data extraction 
 * from responses to AJAX calls.
 *
 * dkc - 04/26/2006
 *-------------------------------------------------*/
//----------------------------------------------------
// basic data extraction utilites...


/***************************************** 
 * text based extractor that locates the  
 * content of a specific div (identifed by 
 * the elements id attribute) and then 
 * extract all data from that div.
 */
function filterText(text,divId){
	var capture = 0;
	var respText = '';
	var pattern = '<div[ ]+id="' + divId + '"[^>]*>';

	var re = new RegExp(pattern,'i');
	var nest = 0;
	
	// split and walk text as lines		
	var lines = text.split('\n');
	for(l in lines) {
		line = lines[l];

		// if capturing....
		if (capture) {
			// watch for nested divs
			if ( line.match(/^.*<div.*$/))
				nest += 1;

			// test for end of capture
			if ( line.match(/^.*<\/div>.*$/)) {
				nest -= 1;
				// if nesting done, end capture
				if (nest == 0)
					capture = 0;
			}
			
			// if we're still on, record text
			if(capture)
				respText = respText + line + '\n';
		}
		// test for capture trigger
		if(line.match(re)) {
			capture = 1;
			nest += 1;
		}
	}
	// return results	
	return respText;
}

/** simple dom based extract from text node */ 
function getTextNodeValue(n) {
	rv = "";
	if ( n.firstChild ) {
		rv = n.firstChild.data;
	} else {
		rv = '';
	}
	return rv;
}

function getFirstChildNodeByName(node,name) {
	rv = null;
	// get the list of named nodes 
	nl = node.getElementsByTagName(name); 
	
	// we need the first (if any)
	if (nl.length > 0)
		rv = nl.item(0);
		
	// done	
	return rv; 
}

// put the other two together and get
// the text value of a child node.
function getChildNodeText(node,chName){
	return getTextNodeValue(getFirstChildNodeByName(node,chName));
}
